package BC;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemWriter;

import java.io.*;

import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

public class DerToPem {
    public  static X509Certificate getDerCert(String path) throws IOException, CertificateException, NoSuchProviderException {
        //加载BC
        Security.addProvider( new BouncyCastleProvider() );
        //读DER证书
        File file = new File(path);
        long filesize = file.length();
        FileInputStream fis = new FileInputStream(file);
        byte[] cert = new byte[(int) filesize];
        int offset = 0;
        int numRead = 0;
        while (offset < cert.length && (numRead = fis.read(cert, offset, cert.length - offset)) >= 0) {
            offset += numRead;
        }
        fis.close();

        //输出X509格式证书
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509","BC");//获取工厂实例
        Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(cert));//用文件流读入证书
        X509Certificate x509Certificate = (X509Certificate)certificate;
        return x509Certificate;
    }

    public static void writePemCert(String path, X509Certificate x509Certificate) throws IOException, CertificateEncodingException {
        //加载BC
        Security.addProvider( new BouncyCastleProvider() );

        //BC转化PEM格式证书
        StringWriter str = new StringWriter();
        PemWriter pemWriter = new PemWriter(str);
        pemWriter.writeObject(new PemObject("CERTIFICATE",x509Certificate.getEncoded()));
        pemWriter.close();
        str.close();
        FileOutputStream fos;
        fos = new FileOutputStream(path);
        fos.write(str.toString().getBytes());
        System.out.println("Successful!");
    }

    public static void main(String[] args) throws Exception {
        String pathSrc = "lzc_cert_demo.der";
        String pathDst = "lzc_cert_demo.pem";
        String s = pathSrc.substring(pathSrc.length() - 3);
        /*if (!((s.equals("pem")) || (s.equals("crt")) || (s.equals("cer")))) {
            System.out.println("输入错误！");
            System.exit(-1);
        }*/
        X509Certificate certificate  = DerToPem.getDerCert(pathSrc);
        DerToPem.writePemCert(pathDst,certificate);
    }

}